package cn.edu.dgut.Filter;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class EntityManagerFilter implements Filter {

    private EntityManagerFactory emf;

    @Override
    public void init(FilterConfig filterConfig) {
        emf = Persistence.createEntityManagerFactory("MyJPADemoPU");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        String uri = ((HttpServletRequest) request).getRequestURI();
        if (uri.contains("/CreatePerson2") || uri.contains("/login/dgut") || uri.contains("/saveServlet") || uri.contains("/checkServlet")
                || uri.contains("/bindServlet")  || uri.contains("userInfo.jsp")|| uri.contains("/image")
        ) {

            System.out.println("[" + ((HttpServletRequest) request).getRequestURI() + "],EntityManagerFilter拦截成功");

            EntityManager em = emf.createEntityManager();
            EntityTransaction tx = em.getTransaction();

            tx.begin();

            request.setAttribute("_entity.manager", em);

            try {
                chain.doFilter(request, response);
                tx.commit();
            } catch (IOException | ServletException th) {

                tx.rollback();

                throw th;

            } finally {
                em.close();
            }
        } else {
            chain.doFilter(request, response);
        }
    }
        @Override
        public void destroy () {
            emf.close();
        }

}
